package com.juno.cafenoa.util;
import java.io.File;

import android.content.Context;

public class FileCache {
    
    private File cacheDir;
	private Context		mContext;
    
    public FileCache(Context context){
//        Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
        		cacheDir = context.getExternalCacheDir();
        }else {
        	cacheDir = context.getCacheDir();
        }
    	
        if( !cacheDir.exists() )
            cacheDir.mkdirs();
    	        
        this.mContext = context;
    }
    
    public File getFile(String keyUrl ){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
    		String filename;
        File f;
//        AndroidLog.i( "FileCache" ,  url );
//        int index = url.lastIndexOf( "&sid" );
//        url = url.substring( 0 , index );
//        AndroidLog.i( "FileCache" ,"substring  " + url );
        
        if( cacheDir != null ) {
//        	filename=String.valueOf(url.hashCode());
//          f = new File(cacheDir, filename);
        		filename=String.valueOf(keyUrl.hashCode());
        		f = new File(cacheDir, filename);
        }else {
//    		String dir = mContext.getFilesDir().toString() + "/HaeinMessenger";
//        	File cacheDir = new File(dir);
//        	if(!cacheDir.exists())
//        		cacheDir.mkdirs();
//        	String file = dir + String.valueOf(url.hashCode());
//        	f = new File(file);
	    		String dir = mContext.getFilesDir().toString() + "/HaeinMessenger";
	        	File cacheDir = new File(dir);
	        	if(!cacheDir.exists())
	        		cacheDir.mkdirs();
	        	String file = dir + String.valueOf(keyUrl.hashCode());
	        	f = new File(file);
	    	}
    	
        return f;
        
    }
    
    public void clear(){
    	String fileName = mContext.getFilesDir().toString() + "/HaeinMessenger";
    	File cacheDir = new File(fileName);
        File[] files = cacheDir.listFiles();
        if( files != null ){
	        for(File f:files)
	            f.delete();
        }
    }

}